#!/usr/bin/python

import psycopg2
import subprocess
import sys
import os
import re
import getpass
import argparse

parser = argparse.ArgumentParser(description= """

DEPRECATED: This script shouldn't be used. Use demultiplex_service_fastq.py instead.

DESCRIPTION
    
    Demultiplex the fastq file associated with a service id (typically an SLX id).
    Fastq file, barcodes and output files are retrieved from view_fastq_for_library
    Note that the output file names are produced by view_fastq_for_library.
    
EXAMPLE
    demultiplex_service.py -s SLX-4970

DEPENDS-ON:
    - ~/psycopgpass & psycopg2
    - demux_fuzzy.py on the server where the repository is.
    - ssh/scp without password prompt
    
DEPENDS-ON-ME:

TODO:

""", formatter_class= argparse.RawTextHelpFormatter)

parser.add_argument('--service', '-s',
                   required= True,
                   help='''The service ID for which to retrieve
fastq file and barcode information. This string will query view_fastq_for_library
                   ''')

parser.add_argument('--username', '-u',
                   required= False,
                   default= None,
                   help='''Username to connect to remote host. Default is None which
means the current username will be used.
                   ''')

parser.add_argument('--hostname', '-H',
                   required= False,
                   default= '143.65.169.175',
                   help='''Hostname where fastqfiles are stored.
Default is 143.65.169.175 (uk-cri-lsrv10)
                   ''')

parser.add_argument('--repository', '-r',
                   required= False,
                   default= '/data01/sblab/users/berald01/repository/original/fastq',
                   help='''Repository directory where fastqfiles are stored on the host.
Default '/data01/sblab/users/berald01/repository/original/fastq'.
                   ''')

parser.add_argument('--destdir', '-d',
                   required= False,
                   default= '/data01/sblab/users/berald01/repository/derived/fastq',
                   help='''Repository directory where demultiplexed fastqfiles will go,
unless the sample sheet contains delmultiplexed file name with path. In fact destdir
is simply the dir where demux_fuzzy.py will be executed.)
Default '/data01/sblab/users/berald01/repository/derived/fastq'. This dir *must* exist.
                   ''')

args = parser.parse_args()
# -----------------------------------------------------------------------------

def get_psycopgpass():
    """
    Read file ~/.psycopgpass to get the connection string to pass to
    psycopg2.connect()
    """
    import os
    conn= open(os.path.join(os.getenv("HOME"), '.psycopgpass'))
    conn= conn.readlines()
    conn_args= [x.strip() for x in conn if x.strip() != '' and x.strip().startswith('#') is False][0]
    return(conn_args)

conn= psycopg2.connect(get_psycopgpass())
cur= conn.cursor()

if args.username is None:
    args.username= getpass.getuser()

# -----------------------------------------------------------------------------

sql= """SELECT DISTINCT fastqfile, array_to_string(array_agg(demux_sheet), E'\n') FROM view_fastq_for_library WHERE service_id = %s AND fastqfile != 'No fastq file found' AND fastqfile is not null AND barcode_id != 'not_multiplexed' GROUP BY fastqfile"""
print(cur.mogrify('\n' + sql, (args.service,)))
cur.execute(sql, (args.service,))
demuxdata=cur.fetchall()

if demuxdata == []:
    sys.exit('\ndemultiplex_service.py: No service or no fastqfile found for service id "%s". Exiting...\n' %(args.service))

for fq in demuxdata:
    "Write out demultiplex files"
    samplesheet= fq[0] + '.demux.txt'
    fh= open(os.path.join('/tmp', samplesheet), 'w')
    fh.write(fq[1])
    fh.close()
    "Send to remote host and execute demux_fuzzy.py"
    cmd= """scp %(samplesheet)s %(username)s@%(hostname)s:%(destdir)s; rm %(samplesheet)s""" %{'samplesheet':os.path.join('/tmp', samplesheet), 'username':args.username, 'hostname':args.hostname, 'destdir':args.destdir}
    print(cmd)
    p= subprocess.Popen(cmd, shell= True)
    p.wait()
    cmd= """ssh %(username)s@%(hostname)s "
            set -e;
            source ~/.bash_profile;
            cd %(destdir)s;
            gunzip -c %(fastqfile)s | demux_fuzzy.py -f - -s %(samplesheet)s --pgupload --report > %(logfile)s
    " """ %{'username':args.username, 'hostname':args.hostname, 'destdir':args.destdir, 'fastqfile':os.path.join(args.repository, fq[0]), 'samplesheet':samplesheet, 'logfile':os.path.splitext(samplesheet)[0] + '.log'}
    print(cmd)
    p= subprocess.Popen(cmd, shell= True)
sys.exit()
